<?php
class Socket {
	private $_rSocket = null;
	private $_rConn = null;
	private $_aLog = null;
	
	public function create($iDomain = AF_INET, $iType = SOCK_STREAM, $iProtocol = SOL_TCP) {
		$rSocket = socket_create ( $iDomain, $iType, $iProtocol );
		if ($rSocket) {
			$this->_rSocket = $rSocket;
			return $rSocket;
		} else {
			$this->_aLog [] = socket_strerror ( socket_last_error () );
			return false;
		}
	}
	
	public function connect($sHost, $sPort, $rSocket = null) {
		if ($rSocket == null) {
			if ($this->_rSocket == null) {
				$rSocket = self::create ();
			} else {
				$rSocket = $this->_rSocket;
			}
		} else {
			$this->_rSocket = $rSocket;
		}
		
		$rConn = socket_connect ( $rSocket, $sHost, $sPort );
		if ($rConn) {
			$this->_rConn = $rConn;
			return $rConn;
		} else {
			$this->_aLog [] = socket_strerror ( socket_last_error () );
			return false;
		}
	}
	
	public function send($sString, $rSocket = null) {
		if ($rSocket == null) {
			if ($this->_rSocket == null) {
				$rSocket = self::create ();
			} else {
				$rSocket = $this->_rSocket;
			}
		} else {
			$this->_rSocket = $rSocket;
		}
		
		$iResult = socket_write ( $rSocket, $sString, strlen ( $sString ) );
		if ($iResult === false) {
			$this->_aLog [] = socket_strerror ( socket_last_error () );
			return false;
		} else {
			$this->_aLog [] = socket_read ( $rSocket, 1024 );
			return true;
		}
	}
}
?>